/*
 * @Description: 一些全局的公用方法
 * @Author: yilingsj（315800015@qq.com）
 * @Date: 2021-04-09 14:23:09
 * @LastEditors: liu (1427179517@qq.com)
 * @LastEditTime: 2022-02-14 22:09:37
 */
const GLOBALCONFIG = require('@/config')
import color from '@/uview-ui/libs/function/color.js'

const hostImg = 'http://qn.kaifengwenhua.wang/'
/**
 * @author: yiling (315800015@qq.com)
 * @description: 修复第4位小数四舍五入的bug
 * @param {Number} digits 传入的值
 * @return {*}
 * @Date: 2020-07-15 11:29:47
 */
Number.prototype.round = function(digits) {
	digits = Math.floor(digits)
	if (isNaN(digits) || digits === 0) {
		return Math.round(this)
	}
	if (digits < 0 || digits > 16) {
		throw 'RangeError: Number.round() digits argument must be between 0 and 16'
	}
	var multiplicator = Math.pow(10, digits)
	return Math.round(this * multiplicator) / multiplicator
}
Number.prototype.toFixed = function(digits) {
	digits = Math.floor(digits)
	if (isNaN(digits) || digits === 0) {
		return Math.round(this).toString()
	}
	var parts = this.round(digits).toString().split('.')
	var fraction = parts.length === 1 ? '' : parts[1]
	if (digits > fraction.length) {
		fraction += new Array(digits - fraction.length + 1).join('0')
	}
	return parts[0] + '.' + fraction
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 接收变量并判断其类型
 * @param {Object,Number,Array,String,Null,Undefined,Boolean,Function} val 接收变量
 * @return {*}
 * @Date: 2021-04-30 14:53:06
 */
function variableType(val) {
	const valEnum = {
		'[object String]': 'String',
		'[object Number]': 'Number',
		'[object Array]': 'Array',
		'[object Object]': 'Object',
		'[object Null]': 'Null',
		'[object Undefined]': 'Undefined',
		'[object Boolean]': 'Boolean',
		'[object Function]': 'Function',
	}
	return valEnum[Object.prototype.toString.call(val)]
}
/**
 * @author: yiling (315800015@qq.com)
 * @description: 四则运算
 * @param {*}
 * @return {*}
 * @Date: 2020-07-15 11:29:47
 */
const calculate = {
	add: function(num1, num2) {
		const sum = parseFloat(parseFloat(num1 || 0) + parseFloat(num2 || 0))
		return sum.toFixed(2)
	},
	multiply: function(num1, num2) {
		// 乘
		const sum = parseFloat(num1 * num2)
		return sum.toFixed(2)
	},
	subtract: function(num1, num2) {
		// 减
		const sum = parseFloat(num1 - num2)
		return sum.toFixed(2)
	},
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 获取图片地址
 * @param {String} src 图片路径，可能为空
 * @param {String} type 默认图片：img|video
 * @return {*}
 * @Date: 2021-04-01 08:50:41
 */
function getPictureSrc(src, type) {
	const defaultSrc = hostImg + '/1617238031_eANyv.svg' // 默认图
	function filterUrl(url) {
		return url.replace('//uploads', '/uploads')
	}
	if (src) {
		if (!src.match(/svg|png|gif|jp(e)?g/) && !type) {
			console.log('非图片', type)
			return filterUrl(defaultSrc)
		}
		if (!src.match(/http/)) {
			return filterUrl(hostImg + src)
		}
		return filterUrl(src)
	}
	return filterUrl(defaultSrc)
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 复制文本
 * @param {Object,String} options 需要复制的内容，必填
 * @return {*}
 * @Date: 2021-04-09 14:27:43
 */
function copyText(options) {
	let data = ''
	let success = null // 成功的回调
	let fail = null // 失败的回调
	if (options) {
		if (options.constructor === Object) {
			data = options.data
			success = options.success
			fail = options.fail
		}
		if (options.constructor === String) {
			data = options
		}
	}
	if (!data) {
		uni.showToast({
			title: '请先设置复制内容',
			duration: 2000,
			icon: 'none',
		})
		return
	}
	if (typeof data !== 'string') {
		uni.showToast({
			title: '复制内容仅支持字符串类型！',
			duration: 2000,
			icon: 'none',
		})
		return
	}
	// #ifdef H5
	uni.showToast({
		title: '哎唷~，暂不支持哦！',
		duration: 2000,
		icon: 'none',
	})
	// #endif
	// #ifndef H5
	uni.setClipboardData({
		data: data,
		complete: (res) => {
			const {
				errMsg
			} = res
			if (errMsg !== 'setClipboardData:ok') {
				console.log('复制失败')
				fail && fail(res)
			} else {
				success && success(res)
			}
			console.log('complete', res)
		},
	})
	// #endif
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 打电话
 * @param {String} tel 手机号
 * @return {*}
 * @Date: 2021-04-09 16:43:38
 */
function makeACall(tel) {
	if (!tel) {
		uni.showToast({
			title: '请先设置手机号',
			duration: 2000,
			icon: 'none',
		})
		return
	}
	const newTel = tel.toString()
	// 获取设备平台
	const platform = uni.getSystemInfoSync().platform
	console.log('platform=', platform)

	uni.makePhoneCall({
		phoneNumber: newTel,
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 封装模态弹窗
 * @param {String} title 标题
 * @param {String} content 内容
 * @param {String} confirmColor 确认按钮的颜色
 * @param {String} cancelText 取消按钮的文字
 * @param {String} confirmText 确定按钮的文字
 * @param {Function} confirm 点击确认时的回调
 * @param {Function} cancel 点击取消时的回调
 * @return {*}
 * @Date: 2021-04-11 09:04:11
 */
function showModal({
	title,
	content,
	confirmColor,
	cancelText,
	confirmText,
	confirm,
	cancel
} = {}) {
	uni.showModal({
		title: title || '提示',
		content: content || '',
		confirmColor: confirmColor || color['primary'],
		cancelText: cancelText || '取消',
		confirmText: confirmText || '确定',
		complete: (res) => {
			if (res.confirm) {
				console.log('用户点击确定')
				confirm && confirm(res)
			} else if (res.cancel) {
				console.log('用户点击取消')
				cancel && cancel(res)
			}
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 封装toast
 * @param {Object, String} options 传递参数
 * @return {*}
 * @Date: 2021-04-11 10:35:54
 */
function toast(options) {
	let title = ''
	let callback = null
	let duration = 2000
	if (options.constructor === Object) {
		title = options.title
		callback = options.callback
		duration = options.duration || 2000
	}
	if (options.constructor === String) {
		title = options
	}
	uni.showToast({
		title: title || '操作中...',
		icon: 'none',
		duration: duration,
		mask: true,
		complete: (res) => {
			setTimeout(() => {
				callback && callback(res)
			}, duration - 500)
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 封装loading
 * @param {type}
 * @return {type}
 * @Date: 2020-09-05 21:52:02
 */
function showLoading(options) {
	let title = ''
	let callback = null
	if (options) {
		if (options.constructor === Object) {
			title = options.title
			callback = options.callback
		}
		if (options.constructor === String) {
			title = options
		}
	}
	uni.showLoading({
		title: title || '加载中...',
		mask: true,
		complete: (res) => {
			callback && callback(res)
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 唤醒微信支付弹窗
 * @param {Object} data 支付参数
 * @param {Function} callback 回调
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
 * @return:
 * @Date: 2020-07-29 11:30:35
 */
const wxPayment = ({
	data,
	callback,
	success,
	fail
} = {}) => {
	console.log('data', data)
	uni.requestPayment({
		provider: 'wxpay',
		timeStamp: data.timeStamp || String(Date.now()),
		nonceStr: data.nonceStr,
		package: data.package,
		signType: data.signType || 'MD5',
		paySign: data.paySign,
		success: (res) => {
			console.log('success:' + JSON.stringify(res))
			success && success(res)
		},
		fail: (err) => {
			console.log('fail:' + JSON.stringify(err))
			fail && fail(res)
		},
		complete: (res) => {
			console.log('complete=', res)
			callback && callback(res)
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 微信官方登录
 * @param {Object} data object
 * @param {Function} callback function
 * @return {void}
 * @Date: 2020-07-08 10:41:45
 */
const wxLogin = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			complete: (res) => {
				resolve(res)
			},
		})
	})
}
/**
 * @author: yiling (315800015@qq.com)
 * @description: 获取用户信息(202102月微信密文有更新)
 * @param {Function} success 成功的回调
 * @return {*}
 * @Date: 2021-04-15 13:17:37
 */
const getUserProfile = (success) => {
	uni.getUserProfile({
		desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
		success: (res) => {
			console.log('res=', res)
			uni.login({
				// provider: 'weixin',
				success: (loginRes) => {
					console.log('loginRes', loginRes)
					const data = {
						code: loginRes.code,
						...res,
					}
					success && success(data)
				},
				fail: (loginRes) => {
					console.log('loginRes', loginRes)
				},
			})
		},
		fail: (err) => {
			console.log('获取用户信息失败err-', err)
			// getUserProfile(success)
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 高德地图逆解析
 * @param {String} key 密钥key
 * @param {String, Number} longitude 经度
 * @param {String, Number} latitude 纬度
 * @param {Function} callback 成功的回调
 * @param {Function} fail 失败的回调
 * @return {*}
 * @Date: 2020-10-23 14:00:51
 */
function getAmapCode({
	key,
	longitude,
	latitude,
	callback,
	fail
}) {
	const newKey = '536d415b503536ad27e4fdd0e1dfd9b0' // web服务端
	const url = 'https://restapi.amap.com/v3/geocode/regeo?key=' + newKey + '&location=' + longitude + ',' + latitude
	if (!longitude) {
		toast('请传入经度！')
		return
	}
	if (!latitude) {
		toast('请传入纬度！')
		return
	}
	return uni.request({
		url: url,
		success: (res) => {
			console.log('%c 高德地图逆解析', 'color:#f00', res)
			if (res.data.infocode === '10000') {
				callback && callback(res)
			} else {
				toast('高德地图解析异常！')
			}
		},
		fail: (res) => {
			fail && fail(res)
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 获取当前位置
 * @param {*} options
 * @return {*}
 * @Date: 2020-11-24 15:48:55
 */
function getNowLocation(options = {}) {
	const {
		success,
		fail
	} = options
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			console.log('%c 小程序中获取经纬度成功', 'color:#f00', res, Date.now())
			success && success(res)
		},
		fail: (res) => {
			console.log('%c 小程序中获取经纬度 失败', 'color:#f00', res, Date.now())
			if (res.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF') {
				toast('建议检查手机是否开启定位权限')
			} else {
				toast('获取经纬度失败！')
			}
			fail && fail(res)
		},
	})
}
/**
 * @author: yiling (315800015@qq.com)
 * @description: 使用微信内置地图查看位置
 * @param {Number} latitude 纬度，范围为-90~90
 * @param {Number} longitude 经度，范围为-180~180
 * @param {String} name 位置名
 * @param {String} address 地址的详细说明
 * @param {Number} scale 缩放比例，范围5~18
 * @param {Function} success 接口调用成功的回调函数
 * @param {Function} fail 接口调用失败的回调函数
 * @return {*}
 * @Date: 2021-06-20 11:22:17
 */
function openLocation({
	latitude = 29.965212,
	longitude = 121.596686,
	name = '浙江省宁波市海曙区',
	address = '中山东路188号',
	scale = 18,
	success,
	fail,
}) {
	uni.openLocation({
		latitude: Number(latitude),
		longitude: Number(longitude), // 经度 -180~180
		scale: Number(scale),
		name: decodeURIComponent(name),
		address: decodeURIComponent(address),
		success: (res) => {
			console.log('res=', res)
		},
		fail: (err) => {
			console.log('err=', err)
		},
	})
}
/**
 * @author: yiling (315800015@qq.com)
 * @description: 获取微信小程序的权限
 * @param {String} key 字符串key
 * @param {Object} success 成功的对象函数
 * @param {Function} fail 失败函数
 * @return {*}
 * @Date: 2021-05-18 13:45:44
 */
function getSetting({
	key,
	success = {},
	fail
} = {}) {
	// #ifdef MP
	uni.getSetting({
		withSubscriptions: true,
		success: (res) => {
			console.log('getSetting res=', res)
			if (res.authSetting) {
				if (res.authSetting['scope.' + key]) {
					success && success.true && success.true(res)
				} else if (res.authSetting['scope.' + key] === undefined) {
					success && success.undefined && success.undefined(res)
				} else {
					console.log('false ', success && success.false)
					success && success.false && success.false(res)
				}
			}
		},
		fail: (err) => {
			console.log('%c getSetting 失败', 'color:#f00', err, Date.now())
			fail && fail(err)
		},
	})
	// #endif
}
/**
 * @author: yiling (315800015@qq.com)
 * @description: 获取定位权限
 * @param {*} success
 * @return {*}
 * @Date: 2021-05-18 16:10:04
 */
function getSettingUserLocation({
	success
} = {}) {
	getSetting({
		key: 'userLocation',
		success: {
			true: (res) => {
				console.log('有定位权限', res)
				success && success(res)
			},
			false: (res) => {
				console.log('无定位权限', res)
				showModal({
					content: '为了更好的体验，建议开启定位权限',
					confirm: (res2) => {
						if (res2.confirm) {
							wx.openSetting({
								success: (res3) => {
									console.log('重新定位了 openSetting', res3)
									if (res3.authSetting['scope.userLocation']) {
										success && success(res)
									}
								},
							})
						} else if (res2.cancel) {
							console.log('用户点击取消')
						}
					},
					cancel: (res3) => {
						console.log('取消了定位弹窗 openSetting', res3)
						// toast('不开启定位权限无法使用该功能')
					},
				})
			},
			undefined: (res) => {
				console.log('undefined 定位权限', res)
			},
		},
	})
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 捕获await异常
 * @param {*} promise
 * @return {*}
 * @Date: 2021-04-11 11:11:24
 */
const awaitCapture = (promise) => {
	return promise.then((res) => [null, res]).catch((error) => [error, null])
}

/**
 * @author: yiling (315800015@qq.com)
 * @description: 封装路由跳转
 * @param {String} name 路由的name
 * @param {Object} query 路由的query
 * @param {String} type 跳转类型
 * @return {*}
 * @Date: 2021-07-02 18:12:35
 */
function jump({
	name,
	query = {},
	type
} = {}) {
	setTimeout(() => {
		console.log('封装一层跳转 之前', name, ';query=', query, ';path=')
		const path = this.$Router.routesMap.nameMap[name].path
		console.log('封装一层跳转', ';query=', query, ';path=', path, ';type=', type)
		if (type === 'replace') {
			//  uni.redirectTo()
			this.$Router.replace({
				path: path,
				query: query
			})
		} else if (type === 'pushTab') {
			//  uni.switchTab()
			this.$Router.pushTab({
				path: path,
				query: query
			})
		} else if (type === 'replaceAll') {
			// 等同于 uni.reLaunch()
			this.$Router.replaceAll({
				path: path,
				query: query
			})
		} else {
			this.$Router.push({
				path: path,
				query: query
			})
		}
	}, 0)
}
/**
 * @author: yilingsj（315800015@qq.com）
 * @description: 保存图片到系统相册
 * @return {void}
 * @Date: 2020-04-06 14:25:56
 */
function handleSaveImageToPhotosAlbum(src) {
	console.log('src====', src)
	uni.saveImageToPhotosAlbum({
		filePath: src,
		success: (res) => {
			console.log('保存成功=', res)
			// setTimeout是为了防止在苹果手机中一闪而过
			setTimeout(() => {
				uni.showToast({
					title: '保存成功！请到相册中查看',
					icon: 'none',
					duration: 3000,
				})
			}, 0)
		},
		fail: (err) => {
			console.log('保存失败=', err)
			uni.showModal({
				title: '提示',
				content: '保存失败',
				showCancel: false,
			})
		},
		complete: () => {
			console.log('??????')
			uni.hideLoading()
		},
	})
}
/**
 * @author: adu（duhw@5ifengdu.com）
 * @description: 验证是否有保存图片到相册的权限（注意：无法检测系统存储空间的权限！）
 * @param {Function} callback 回调
 * @return {void}
 * @Date: 2020-03-29 19:16:21
 */
function getWritePhotosAlbum(callback) {
	// #ifdef MP
	getSetting({
		key: 'writePhotosAlbum',
		success: {
			true: (res) => {
				callback && callback()
			},
			undefined: () => {
				uni.showModal({
					title: '提示',
					content: '您未开启保存图片到相册的权限，请点击确定去开启权限！',
					success: (res) => {
						if (res.confirm) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: (res) => {
									callback && callback()
									console.log('授权下载成功', res)
								},
								fail: (res) => {
									console.log('您没有授权 fail=', res)
									// this.setDisabled(false, 'isDisabledSave');
									uni.hideLoading()
									uni.showToast({
										title: '您没有授权，无法保存到相册',
										icon: 'none',
									})
								},
							})
						} else {
							console.log('取消了')
							// this.setDisabled(false, 'isDisabledSave')
							uni.hideLoading()
						}
					},
				})
			},
			false: () => {
				uni.showModal({
					title: '提示',
					content: '到设置中开启权限后才能保存哦~',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (res) => {
									if (res.authSetting['scope.writePhotosAlbum']) {
										console.log('false success res=', res)
										callback && callback()
									} else {
										uni.showToast({
											title: '您没有授权，无法保存到相册！',
											icon: 'none',
										})
										// this.setDisabled(false, 'isDisabledSave')
										uni.hideLoading()
									}
								},
								fail: (res) => {
									// this.setDisabled(false, 'isDisabledSave')
									uni.hideLoading()
									console.log('false file res=', res)
								},
							})
						} else {
							console.log('取消了')
							// this.setDisabled(false, 'isDisabledSave')
							uni.hideLoading()
						}
					},
				})
			},
		},
	})
	// #endif

	// #ifndef MP
	callback && callback()
	// #endif
}

/**
 * @author: yiling (315800015@qq.com)
 * @description: 重置form表单字段
 * @param {Object} data form对象
 * @return {*}
 * @Date: 2021-05-12 10:05:57
 */
export function clearForm(data) {
	console.log('data========', data)
	if (variableType(data) !== 'Object') {
		console.log('data必须要是对象')
		return
	}
	Object.keys(data).forEach((item) => {
		if (variableType(data[item]) === 'String') {
			data[item] = ''
		}
		if (variableType(data[item]) === 'Null') {
			data[item] = null
		}
		if (variableType(data[item]) === 'Boolean') {
			data[item] = false
		}
		if (variableType(data[item]) === 'Undefined') {
			data[item] = undefined
		}
		if (variableType(data[item]) === 'Number') {
			data[item] = 0
		}
		if (variableType(data[item]) === 'Object') {
			console.log('是对象')
			clearForm(data[item])
		}
		if (variableType(data[item]) === 'Array') {
			data[item] = []
		}
		return item
	})
	return data
}

// 时间戳转换时间
export function formatTime(timeStamp = Date.now()) {
	const date = new Date(timeStamp);
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	const hour = date.getHours().toString().padStart(2, '0');
	const minute = date.getMinutes().toString().padStart(2, '0');
	const second = date.getSeconds().toString().padStart(2, '0');

	return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}


export {
	calculate,
	copyText,
	makeACall,
	showModal,
	toast,
	showLoading,
	getAmapCode,
	awaitCapture,
	wxPayment,
	getPictureSrc,
	wxLogin,
	getUserProfile,
	variableType,
	getNowLocation,
	getSetting,
	getSettingUserLocation,
	openLocation,
	jump,
	handleSaveImageToPhotosAlbum,
	getWritePhotosAlbum,
}